package com.android.basemvvm

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.base_network.exception.ExceptionHandle
import com.android.basemvvm.event.Message
import com.android.basemvvm.event.SingleLiveEvent
import com.blankj.utilcode.util.LogUtils

import kotlinx.coroutines.*


open class BaseViewModel : ViewModel(), IViewModel, DefaultLifecycleObserver {

    val defUI: UIChange by lazy { UIChange() }

    var mBVOnExceptionListener: BVOnExceptionListener? = null

    /**
     * 所有网络请求都在 viewModelScope 域中启动，当页面销毁时会自动
     * 调用ViewModel的  #onCleared 方法取消所有协程
     */
    fun launch(block: suspend CoroutineScope.() -> Unit) =
        viewModelScope.launch(MVVMLin.netException) { block() }

    /**
     * UI事件
     */
    inner class UIChange {
        val showDialog by lazy { SingleLiveEvent<String>() }
        val dismissDialog by lazy { SingleLiveEvent<Unit>() }
        val msgEvent by lazy { SingleLiveEvent<Message>() }
    }

    override fun showLoading(text: String) {
        defUI.showDialog.postValue(text)
    }

    override fun dismissLoading() {
        defUI.dismissDialog.postValue(Unit)
    }

    interface BVOnExceptionListener {
        fun onListener(code: Int,message: String)
    }

    fun setBVOnExceptionListener(exceptionListener: BVOnExceptionListener){
        mBVOnExceptionListener = exceptionListener
    }
}